import os
import warnings
from typing import List
from sentence_transformers import SentenceTransformer

class EmbeddingModel:
    _instance = None  # 类变量，保存单例实例
    _model = None     # 类变量，保存加载的模型
    _dimension = 384  # 类变量，嵌入维度

    def __new__(cls, model_name: str = 'Qwen/Qwen3-Embedding-4B'):
        """单例模式的核心实现"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._initialize_model(model_name)  # 初始化模型
        return cls._instance

    @classmethod
    def _initialize_model(cls, model_name: str):
        """类方法，用于初始化模型（只会执行一次）"""
        if cls._model is None:
            os.environ["TOKENIZERS_PARALLELISM"] = "false"
            warnings.filterwarnings("ignore", message="No sentence-transformers model found with name*")

            try:
                # 尝试从本地缓存加载
                cls._model = SentenceTransformer(
                    r"D:\milvusGPT\memgpt_test_0615\memgpt\ebedmodels\Qwen\Qwen3-Embedding-4B"
                )
                print(f"✅ 成功从本地加载模型: {model_name}")
            except Exception as e:
                print(f"⚠️ 本地加载失败 ({e})，尝试从HuggingFace下载...")
                cls._model = SentenceTransformer(model_name)
                print(f"✅ 成功下载模型: {model_name}")

    def get_embedding(self, text: str) -> List[float]:
        """获取单个文本的嵌入向量"""
        return self._model.encode(text, convert_to_tensor=False).tolist()

    def get_embeddings_batch(self, texts: List[str]) -> List[List[float]]:
        """批量获取多个文本的嵌入向量"""
        return self._model.encode(texts, convert_to_tensor=False).tolist()

    @property
    def dimension(self) -> int:
        """获取嵌入向量的维度"""
        return self._dimension